package cn.shadow.server.hanlder;

import cn.shadow.message.Worker;
import cn.shadow.message.WorkerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * 自定义handler需要继承netty的规范
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private final ChannelGroup group;
    private final WorkerFactory factory;

    public NettyServerHandler(WorkerFactory factory, ChannelGroup group) {
        this.group = group;
        this.factory = factory;
    }

    /**
     * 数据读取完毕
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        System.out.println("数据接受完毕");
    }

    /**
     * 异常，一般需要关闭通道
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

    /**
     * 添加
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        Worker worker = factory.newWorker(channel);
        group.add(channel);
        worker.onConnected(); //用户已经连接
    }

    /**
     * 读取来自客户端的消息
     *
     * @param ctx
     * @param byteBuf
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) {

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }
}
